<template>
  <div class="cell-list calendar-head">
    <span @click="setPanelMode">{{ dateString }}</span>
    <div class="icon-wrap">
      <Icon name="arrow_up" @click="upward" />
      <Icon name="arrow_down" @click="downward" />
    </div>
  </div>
</template>

<script>
import { computed, inject, ref } from "vue";
import dayjs from "dayjs";
import Icon from "@/components/Icon";

/* 时间格式化封装
isValid()检查是否已经实例化，返回布尔值；按照传入的格式刷化规则将时间格式化。
 */
const fmt = (fmtString) => (date) =>
  dayjs(date).isValid() ? dayjs(date).format(fmtString) : date;

// 分别对年，月，日做格式化
const fmtDay = fmt("YYYY-MM-DD");
const fmtDate = fmt("YYYY年M月");
const fmtYear = fmt("YYYY年");

export default {
  name: "calendar-head",
  components: { Icon },
  setup(props, ctx) {
    // 接收父组件传值
    const [displayMode, setDisplayMode] = inject("displayMode", [
      ref("date"),
      (v) => v,
    ]);
    const [date, setDate] = inject("date", [ref(new Date()), (v) => v]);

    // 头部时间展示
    const dateString = computed(() => {
      const handler = {
        date: (value) => fmtDate(value),
        month: (value) => fmtYear(value),
        year: (value) => `${value.year()} - ${value.add(15, "year").year()}`,
      };
      return handler[displayMode.value](dayjs(date.value));
    });

    // 切换年月日
    const setPanelMode = () => {
      const mode =
        {
          date: "month",
          month: "year",
          year: "year",
        }[displayMode.value] || "date";
      // 设置头部时间展示
      setDisplayMode(mode);
    };

    // 翻页
    const handleDate = (isAdd) => () => {
      // 下一页
      const setMap = {
        date: {
          value: 1,
          unit: "month",
        },
        month: {
          value: 1,
          unit: "year",
        },
        year: {
          value: 16,
          unit: "year",
        },
      };

      const setter = setMap[displayMode.value];

      const value = isAdd
        ? dayjs(date.value).add(setter.value, setter.unit)  // 下一页
        : dayjs(date.value).subtract(setter.value, setter.unit); // 上一页
      setDate(value.toDate());
    };

    const upward = handleDate(false); // 上翻
    const downward = handleDate(true); // 下翻

    return {
      upward,
      downward,
      setPanelMode,
      dateString,
    };
  },
};
</script>

<style lang="less" rel="stylesheet/less">
.calendar-head {
  position: relative;
  z-index: 1;
  padding: 10px 18px;
  justify-content: space-between;
  align-items: center;

  span {
    color: #fff;
    line-height: 20px;
    cursor: pointer;
  }

  .icon-wrap {
    margin-right: -10px;

    svg {
      cursor: pointer;
      margin: 0 10px;
    }
  }
}
</style>
